package com.wushijia.netty;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageDecoder extends ChannelInboundHandlerAdapter {

  private final Logger logger = LoggerFactory.getLogger(MessageDecoder.class);

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws JsonProcessingException {
    //1：接收到客户端发送的消息msg
    ByteBuf buf = (ByteBuf) msg;
    BaseMessage baseMessage = MessageUtils.getBaseMessage(buf);
    //2：消息解码
    logger.info("received message form client:" + baseMessage);
    //3：定义回复消息体
    BaseMessage responseMessage = new BaseMessage(baseMessage.getMessageId() + 1,
        "response from server", new Date());
    logger.info("send response message for client:" + responseMessage);
    //4：消息编码
    ByteBuf byteBuf = MessageUtils.getByteBuf(responseMessage);
    //5：消息发送，将消息通过ChannelHandlerContext写入Channel
    ctx.writeAndFlush(byteBuf);
  }

  // 连接断开触发实践
  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    logger.error("channel removed");
    super.handlerRemoved(ctx);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    logger.error("channel exception");
    super.exceptionCaught(ctx, cause);
  }
}
